package com.lzh.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 使用esConfig创建高版本的连接客户端
 */
@Configuration
public class EsConfig {

    @Value("${springboot-es.elastichsearch.hostlist}")
    private String hostlist;

    /**
     * 读取配置文件中的内容，创建高版本的客户端，并且交给spring管理
     * @return
     */
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //1.解析Hostlist的配置信息
        String[] split = hostlist.split(",");
        //2.创建httpHost数组，放置es的主机以及端口的配置信息
      HttpHost[] httpHosts =  new HttpHost[split.length];
      //3.循环截取的ip:port进行拼接处理
        for (int i=0;i< split.length;i++){
            String item = split[i];
            httpHosts[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        //创建restHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }
}
